package com.hyh.admin.filter;

import cn.hutool.core.date.DateTime;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hyh.ad.common.constants.Constants;
import com.hyh.ad.common.constants.RedisConstant;
import com.hyh.ad.common.core.domain.login.LoginUser;
import com.hyh.ad.common.core.domain.model.SysUser;
import com.hyh.ad.common.core.redis.CacheClient;
import com.hyh.ad.common.exceptions.BusinessException;
import com.hyh.admin.sys.mapper.SysMenuMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;




/*
 * token验证过滤器
 * 验证token是否有效
 */
@Slf4j
@Component
public class TokenAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private CacheClient cacheClient;

    @Autowired
    private SysMenuMapper sysMenuMapper;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader("token");
        log.info("Received token: {}", token);

        if (token == null || token.isEmpty()) {
            // Token 不存在，放行请求
            filterChain.doFilter(request, response);
            return;
        }

        try {
            // 用 token 从缓存中取出用户信息
            SysUser user = cacheClient.getObject(Constants.TOKEN + token, SysUser.class);
            if (user == null) {
                log.error("Invalid token: no user found");
                throw new RuntimeException("无效签名");
            }
            log.info("Retrieved user: {}", user);

            // 取出用户的权限信息
            String permissions = cacheClient.getObject(RedisConstant.USER_PERMISSION_PREFIX + user.getId());


            log.info("Retrieved permissions: {}", permissions);

            // 封装用户信息和权限信息到 LoginUser 对象中
            LoginUser loginUser = new LoginUser(user, sysMenuMapper.selectAuthentication(user.getId()));

            // 存入 SecurityContextHolder
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                    loginUser, null, loginUser.getAuthorities());
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);

            // 刷新 token 和权限信息的过期时间
            cacheClient.setObject(Constants.TOKEN + token, user, Constants.TOKEN_EXPIRATION, TimeUnit.MINUTES);
            cacheClient.setObject(RedisConstant.USER_PERMISSION_PREFIX + user.getId(), permissions, Constants.TOKEN_EXPIRATION, TimeUnit.MINUTES);

        } catch (Exception e) {
            String Msg = "请求访问："+ request.getRequestURI() + " ，认证失败，无法访问该资源...";
            log.error("{}{}", Msg, "请求时间：" + DateTime.now());
            throw new BusinessException(HttpStatus.HTTP_UNAUTHORIZED,Msg);
        }

        // 继续过滤链
        filterChain.doFilter(request, response);
    }
}
